04 / 07

What is the difference between id and class ?

Difference Between id and class in HTML

In HTML, both id and class are used to uniquely identify or group elements, but they serve different purposes. An id is meant to uniquely identify a single element on a page, while a class can be shared by multiple elements to apply common styles or behaviors.

Example: Using id and class
Key Differences Between id and class
  1. 1

    id is unique within a page; no two elements should share the same id.

  2. 2

    class can be used on multiple elements to apply the same styles or behavior.

  3. 3

    In CSS, id is selected using # (e.g., #header), while class is selected using . (e.g., .highlight).

  4. 4

    In JavaScript, getElementById() is used for id, while getElementsByClassName() or querySelectorAll() is used for class.

  5. 5

    Use id for a single, unique element (like navigation bar, footer).

  6. 6

    Use class for reusable styling or grouping elements (like buttons, highlighted text).